package 分布式系统中的对象传输;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class 对象传输
{

    // 1. 定义可序列化的 DTO 对象
    public static class OrderDTO implements Serializable {
        private static final long serialVersionUID = 1L;//指定版本号：当你先序列化了一个OrderDTO对象，而后修改了OrderDTO类，比如删除或修改了某些字段，反序列化时，会发现文件中的版本号与类的版本号不一致，会报错，应该手动指定。该变量名称，修饰符是固定的
        private String orderId;
        private List<Product> products;
        private transient int id;//transient关键字表示该属性不会被序列号

        public OrderDTO(String orderId, List<Product> products) {
            this.orderId = orderId;
            this.products = products;
        }

        public String getOrderId() {
            return orderId;
        }

        public List<Product> getProducts() {
            return products;
        }
    }

    // 2. 可序列化的 Product 类
    public static class Product implements Serializable {
        private String productId;
        private String name;

        public Product(String productId, String name) {
            this.productId = productId;
            this.name = name;
        }

        public String getProductId() {
            return productId;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "Product{" +
                    "productId='" + productId + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws Exception {
        // 模拟服务A发送数据

        // 创建产品列表
        List<Product> productList = new ArrayList<>();
        productList.add(new Product("P001", "Laptop"));
        productList.add(new Product("P002", "Mouse"));

        // 构建订单对象
        OrderDTO order = new OrderDTO("ORDER_001", productList);

        // 序列化为字节数组
        byte[] serializedData = serialize(order);

        // 模拟网络传输（这里只是内存中传递）
        byte[] receivedData = serializedData;

        // 模拟服务B接收数据
        OrderDTO deserializedOrder = (OrderDTO) deserialize(receivedData);

        // 输出结果
        System.out.println("Received Order ID: " + deserializedOrder.getOrderId());
        for (Product p : deserializedOrder.getProducts()) {
            System.out.println("Product: " + p);
        }
    }

    // 序列化工具方法
    public static byte[] serialize(Serializable obj) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            return bos.toByteArray();
        }
    }

    // 反序列化工具方法
    public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        }
    }
}